<template>
  <a-modal
    :title="dialogModel.depStatusText + '用户组'"
    :visible="dialogModel.depVisible"
    v-bind="commonDlgProps"
    :width="600"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-form-item label="父级用户组">
          <a-tree-select
            style="width: 100%"
            :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
            :treeData="groupTree"
            treeDefaultExpandAll
            dropdownMatchSelectWidth
            :disabled="dialogModel.depStatus === 'edit'"
            v-decorator="['parentId', { rules: [{ required: true, message: '父级用户组不能为空' }] }]"
          >
            <span slot="title" slot-scope="p">
              {{ p.name }}
            </span>
          </a-tree-select>
        </a-form-item>
        <a-form-item label="用户组名称" v-bind="validator.nameValidProps">
          <s-input
            :limit="128"
            v-decorator="[
              'name',
              {
                rules: [
                  { required: true, message: '用户组名称不能为空', whitespace: true },
                  { validator: validator.nameValidator }
                ]
              }
            ]"
          />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { asyncValidateMixin, dialogMixin } from '@/utils/mixin';
import SInput from '@/components/Input';
import { addGroupTree, editGroupTree, validateGroup } from '@/api/authenticationCenter/config/userGroup';

export default {
  name: 'GroupForm',
  mixins: [dialogMixin, asyncValidateMixin],
  components: {
    SInput
  },
  data() {
    return {
      form: this.$form.createForm(this),
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 4
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 20
        }
      },
      confirmLoading: false,
      currentRecord: {
        id: null
      }
    };
  },
  props: {
    groupTree: {
      type: Array,
      required: true,
      default: () => []
    },
    appId: {
      type: [Number, String],
      required: true
    }
  },
  created() {
    // this.form = this.$form.createForm(this);
  },
  methods: {
    add(record) {
      this.operateDialog({
        name: 'dep',
        visible: true,
        status: 'add'
      });
      this.$nextTick(() => {
        this.form.setFieldsValue({
          parentId: record.id
        });
        this.initAsyncValidateMixin(0, record.id);
        console.log(this.form.getFieldsValue());
      });
    },
    edit(record) {
      this.currentRecord = record;
      this.operateDialog({
        name: 'dep',
        visible: true,
        status: 'edit'
      });
      this.$nextTick(() => {
        this.form.setFieldsValue({
          parentId: record.parentId,
          name: record.name
        });
        this.initAsyncValidateMixin(record.id, record.parentId);
        console.log(this.form.getFieldsValue());
      });
    },
    handleOk() {
      const fieldNames = this.$_asyncValidateMixin_fieldsFilter(this.form.getFieldsValue());
      // 触发表单验证
      this.form.validateFields(fieldNames, (err, values) => {
        // 验证表单没错误
        if (!err) {
          console.log('form values', values);
          const model = {
            ...values,
            ...this.form.getFieldsValue(),
            appId: this.appId
          };
          this.confirmLoading = true;
          if (this.dialogModel.depStatus === 'add') {
            addGroupTree(model)
              .then(res => {
                if (res) {
                  this.handleCancel();
                  this.$emit('ok');
                  this.$message.success(res.message);
                  this.confirmLoading = false;
                }
              })
              .catch(() => {
                this.confirmLoading = false;
              });
          } else {
            editGroupTree({
              ...model,
              id: this.currentRecord.id
            })
              .then(res => {
                if (res) {
                  this.handleCancel();
                  this.$emit('ok');
                  this.$message.success(res.message);
                  this.confirmLoading = false;
                }
              })
              .catch(() => {
                this.confirmLoading = false;
              });
          }
        }
      });
    },
    handleCancel() {
      this.form.resetFields();
      this.operateDialog({
        name: 'dep',
        visible: false
      });
    },

    initAsyncValidateMixin(id, parentId) {
      this.$_asyncValidateMixin_init([
        {
          fieldName: 'name',
          caller: validateGroup,
          extraParams: {
            id,
            parentId,
            appId: this.appId
          }
        }
      ]);
    }
  },
  mounted() {}
};
</script>
